package com.xingfly.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 验证码服务类
 * 缓存验证码到Redis中
 * Created by SuperS on 2016/12/16.
 */
@Service
public class CaptchaService {
    public static final String KEY_ACCOUNT = "captcha:account:";
    public static final String KEY_RESET = "captcha:rest:";
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    /**
     * 创建验证码
     *
     * @param key     key
     * @param captcha 验证码
     */
    public void create(String keyName,String key, String captcha) {
        //存储验证码
        redisTemplate.opsForValue().set(keyName + key, captcha);
        //设置验证码过期时间120秒钟
        redisTemplate.expire(keyName + key, 120, TimeUnit.SECONDS);

    }

    /**
     * 验证码失效
     */
    public void delete(String keyName,String key) {
        redisTemplate.expire(keyName + key, 0, TimeUnit.SECONDS);
    }

    /**
     * 通过key获取验证码
     *
     * @param key key
     */
    public String get(String keyName,String key) {
        return redisTemplate.opsForValue().get(keyName + key);
    }

    /**
     * 验证验证码是否为真
     * 将验证码转换为大写
     *
     * @param inputCaptcha 输入验证码
     * @param captcha      验证码
     */
    public boolean verification(String inputCaptcha, String captcha) {
        return inputCaptcha.toUpperCase().equals(captcha.toUpperCase());
    }

}
